15 附录:更多有序集合操作命令

查询有序集合的总个数

语法:zcard key 示例:

127.0.0.1:6379> zcard zset1
(integer) 4

查询 score 区间内的元素个数

语法:zcount key min max 示例:

127.0.0.1:6379> zcount zset1 0 10
(integer) 4

累加元素的 score 值

语法:zincrby key increment member 示例:

127.0.0.1:6379> zscore zset1 redis #查询 zset1 的 score 值
"1"
127.0.0.1:6379> zincrby zset1 2 redis #累加 score 值
"3"
127.0.0.1:6379> zscore zset1 redis
"3"

查询某元素倒序排名

语法:zrevrank key member 示例:

127.0.0.1:6379> zrevrank zset1 python #倒序查询
(integer) 0
127.0.0.1:6379> zrange zset1 0 -1 #正序列表
1) "redis"
2) "java"
3) "golang"
4) "python"

根据排名删除元素

语法:zremrangebyrank key start stop 示例:

127.0.0.1:6379> zrange zset1 0 -1 #查询所有元素
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zremrangebyrank zset1 0 2 #删除元素
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1 #查询所有元素
1) "python"

删除 score 区间内的元素

语法:zremrangebyscore key min max 示例:

127.0.0.1:6379> zscore zset1 python
"4"
127.0.0.1:6379> zremrangebyscore zset1 4 5
(integer) 1
127.0.0.1:6379> zscore zset1 python
(nil)

复制交集元素到新集合

语法:zinterstore destination numkeys key [key …] [WEIGHTS weight] [AGGREGATE SUM|MIN|MA 参数 numkeys 表示需要几个集合参与查询。 示例:

127.0.0.1:6379> zrange zset1 0 -1
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zrange zset2 0 -1
1) "redis"
2) "db"
127.0.0.1:6379> zinterstore zset3 2 zset1 zset2
(integer) 1
127.0.0.1:6379> zrange zset3 0 -1
1) "redis"

复制并集元素到新集合

语法:zunionstore destination numkeys key [key …] [WEIGHTS weight] [AGGREGATE SUM|MIN|MA 示例:

127.0.0.1:6379> zrange zset1 0 -1
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zrange zset2 0 -1
1) "redis"
2) "db"
127.0.0.1:6379> zunionstore zset3 2 zset1 zset2
(integer) 5
127.0.0.1:6379> zrange zset3 0 -1
1) "java"
2) "golang"
3) "redis"
4) "python"
5) "db"